﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FONCREAGROINTEGRAL.Models;

namespace FONCREAGROINTEGRAL.Controllers
{
    public class afiliacionsistemapensionController : Controller
    {
        public SistIntFoncreagroEntities entidades = new SistIntFoncreagroEntities();
        //
        // GET: /afiliacionsistemapension/

        public ActionResult IndexByIdEdit( int id,int id1)
        {
            var query = entidades.AFILIACIONSPs
                .Where(af => af.IdPersonal == id1 && af.IdAfiliacionSP==id);

            var result = (from af in query.ToList()
                          join sp in entidades.SISTEMADEPENSIONES on af.IdSistemaPensiones equals sp.IdSistemaPensiones 
                          join ta in entidades.TIPOAFILIACIONs on af.IdTipoAfiliacion equals ta.IdTipoAfiliacion into consulta
                          from c in consulta.DefaultIfEmpty()
                          select new
                          {
                              Id=af.IdAfiliacionSP,
                              IdPersonal=af.IdPersonal,
                              IdSistemaPensiones = af.IdSistemaPensiones, 
                              NombreSistemapension=sp.Descripcion,
                              NombreCorto=sp.NombreCorto,
                              FechaAfiliacion = string.Format("{0:d}", af.FechaAfiliacion),
                              Cuspp=af.CUSPP,
                              IdEstado = af.Estado,
                              IdTipoAfiliacion = af.IdTipoAfiliacion,
                              NombreAfiliacion = (c == null ? "" : c.NomTipoAfiliacion)

                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }



        public ActionResult Index(int id)
        {
            
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            //string area = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.AFILIACIONSPs
                .Where(asp => asp.IdPersonal == id);
            /*if (!String.IsNullOrEmpty(area))
            {
                query = query.Where(a => (a.Nombre).ToUpper().Contains(area.ToUpper()));
            }*/
            var result = (from asp in query.OrderBy(asp => asp.IdAfiliacionSP).Skip(start).Take(limit).ToList()
                          join sp in entidades.SISTEMADEPENSIONES on asp.IdSistemaPensiones equals sp.IdSistemaPensiones
                          join ta in entidades.TIPOAFILIACIONs on asp.IdTipoAfiliacion equals ta.IdTipoAfiliacion into consulta
                          from c in consulta.DefaultIfEmpty()
                          select new
                          {
                              Id = asp.IdAfiliacionSP,
                              Sistemapension = sp.NombreCorto,
                              Fechaafiliacion = string.Format("{0:d}", asp.FechaAfiliacion),
                              CUSPP = asp.CUSPP,
                              Estado = asp.Estado,
                              Idpersona=asp.IdPersonal,
                              NombreAfiliacion = (c == null ? "" : c.NomTipoAfiliacion)
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /afiliacionsistemapension/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /afiliacionsistemapension/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /afiliacionsistemapension/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection, AFILIACIONSP AFILIACIONSP)
        {
            string strResponse = null;
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {

                    var cafiliacionsp = new AFILIACIONSP();
                    TryUpdateModel(cafiliacionsp, collection.ToValueProvider());
                    //entidades.Rdesactivarcontratoadenda(ccontrato.IdPersonal);
                    cafiliacionsp.Estado = true;
                    entidades.AddToAFILIACIONSPs(cafiliacionsp);
                    entidades.SaveChanges();

                    try
                    {
                        var eafiliacionsp = new AFILIACIONSP();
                        eafiliacionsp = entidades.AFILIACIONSPs.SingleOrDefault(asp => asp.IdPersonal == cafiliacionsp.IdPersonal && 
                        asp.Estado==true && asp.IdAfiliacionSP != cafiliacionsp.IdAfiliacionSP);
                        eafiliacionsp.Estado = false;
                        //TryUpdateModel(eafiliacionsp);
                        entidades.SaveChanges();
                        
                    }

                    catch (Exception e)
                    {
                        strResponse = "{success: false,msg:'" + e.Message + "'}";
                        return Content(strResponse);
                    }
                    strResponse = "{success: true,msg:'Registro Creado Correctamente'}";
                    return Content(strResponse);
                }
                else
                {
                    strResponse = "{success: false,msg:'ModelState Invalid'}";
                    return Content(strResponse);
                }
            }
            catch (Exception e)
            {
                strResponse = "{success: false,msg:'" + e.Message + "'}";
                return Content(strResponse);
            }
        }
        
        //
        // GET: /afiliacionsistemapension/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /afiliacionsistemapension/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection, AFILIACIONSP AFILIACIONSP)
        {
            string strResponse = String.Empty;
            var ta = entidades.AFILIACIONSPs.Single(tia => tia.IdAfiliacionSP == id);
            try
            {

                if (ModelState.IsValid)
                {

                    TryUpdateModel(ta);
                    entidades.SaveChanges();
                    strResponse = "{success: true,msg:'Registro Creado Correctamente'}";
                    return Content(strResponse);
                }
                strResponse = "{success: false,msg:'Fallo en la Creación'}";
                return Content(strResponse);
            }
            catch
            {
                strResponse = "{success: false,msg:'Fallo en la Creación'}";
                return Content(strResponse);
            }
        }

        //
        // GET: /afiliacionsistemapension/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /afiliacionsistemapension/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            string strResponse = null;
            var afiliacionsistemadepensiones = entidades.AFILIACIONSPs.Single(p => p.IdAfiliacionSP == id);
            try
            {
                // TODO: Add delete logic here
                if (afiliacionsistemadepensiones != null)
                {
                    entidades.DeleteObject(afiliacionsistemadepensiones);
                    entidades.SaveChanges();
                    return Content("OK");
                    //return HttpNotFound();
                }
                return Content("Error");
            }
            catch (Exception e)
            {
                strResponse = "{success: false,msg:'" + e.Message + "'}";
                return Content(strResponse);
            }
        }
    }
}
